
const Service = require('egg').Service;
const sha1 = require("sha1")
const APPID = "wx1c2dca946df3d61c"
const SECRET = "c4f1bf90411c96243aa3bc3eaf9f67d3"



class User extends Service {



    async userLogin(u_id, nickName, avatar, sex) {

        var updateUser = await this.app.mysql.update("user", {
            nickName,
            avatar,
            sex,
            status:2

        }, { where: { u_id } })
        if (updateUser.affectedRows == 1) {
            return {
                status: 2,
                message: "ok"
            };
        } else {
            return {
                status: 0
            }

        }

    }



    async addRank(uid, score,type) {

        var rank = await this.app.mysql.insert("question_rank", {
            uid,
            score,
            type,
            praise:0
        })
        if (rank.affectedRows == 1) {
            return {
                status: 1
            }
        } else {
            return {
                status: 0
            }
        }

    }




        async getQuestionData(type, score) {
        var average = 0
        var allResult = await this.app.mysql.select("question_rank", {
            where: {
                type
            }
        })
        if (allResult.length > 0) {
            var allScore = 0
            allResult.forEach((item) => {
                allScore += item.score
            })
            average = parseInt(allScore * 10 / allResult.length) / 10
        }

        var sql = `select count(1) as count from question_rank where score<${score} and type='${type}'`

        var result = await this.app.mysql.query(sql);
           console.log(result[0].count)
        if (allResult && result) {
            return {
                status: 1,
                average,
                count: result[0].count

            }
        } else {
            return {
                status: 0
            }
        }
    }


        async addFeedBack(text, username, avatar, u_id) {

        var feedBack = await this.app.mysql.insert("feedback", {
            text,
            username,
            avatar,
            u_id
        })


          if(feedBack.affectedRows==1){
            return {
                status:1
            }
        }else{
            return {
                status:0
            }
        }

    }

    async getHistory(uid) {

        var historys = await this.app.mysql.select("question_rank", {
            where: {
                uid
            },
            orders:[["score","desc"]]
        })

        if (historys) {

           if (historys.length > 0) {
                for (var i = 0; i < historys.length; i++) {
                    var uid = historys[i].uid
                    var user = await this.app.mysql.get("user", {
                        id: uid
                    })
                    historys[i].user = user
                }
            }



            return {
                status: 1,
                historys
            }
        } else {
            return {
                status: 0
            }
        }
    }
    async addPraise(uid, id) {

        var havePraise = await this.app.mysql.get("have_praise", {
            uid,
            qid: id
        })


        if (havePraise) {
            return {
                status: 2
            }
        } else {
            var addPraise = await this.app.mysql.insert("have_praise", {
                uid,
                qid: id
            })
            var sql = `update question_rank set praise = praise+1 where id=${id}`
            let updatePraise = await this.app.mysql.query(sql);
            if(addPraise.affectedRows==1&&updatePraise.affectedRows==1){
                return {
                    status:1
                }
            }
        }
    }




    async getRank(type, start) {
        var nextStart = -1
        var sum = start * 15
         var sql = `select * from question_rank where type='${type}'  and score in (select max(score) from question_rank where type='${type}' group by uid) group by uid order by score desc limit ${sum}`

        var rankList = await this.app.mysql.query(sql);

      
        if (rankList) {
            if (rankList.length > 0) {
                for (var i = 0; i < rankList.length; i++) {
                    var id = rankList[i].uid
                    var user = await this.app.mysql.get("user", {
                        id
                    })
                    rankList[i].user = user
                }
            }
            if(rankList.length==sum){
                nextStart =sum+1
            }
            return {
                status: 1,
                rankList,
                nextStart
            }
        } else {
            return {
                status: 0
            }
        }
    }


    
    async getQuestion(type) {

        var questionList = await this.app.mysql.select("questions", {
            where: {
                type
            }
        })
        if (questionList) {
            if (questionList.length > 0) {
                for (var i = 0; i < questionList.length; i++) {
                    var q_id = questionList[i].id
                    var options = await this.app.mysql.select("question_detail", {
                        where: {
                            q_id
                        }
                    })
                    questionList[i].options = options
                }
            }
            return {
                status: 1,
                questionList
            }
        } else {
            return {
                status: 0
            }
        }
    }



    
    async getQuestionType() {

        var types = await this.app.mysql.select("question_type", {

        })
        if (types) {
            return {
                status: 1,
                types
            }
        } else {
            return {
                status: 0
            }
        }
    }


    async userAuthLogin(code) {
        const uidUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`
        let result = await this.app.curl(uidUrl, {
            dataType: 'json',
        });
        let openID = result.data.openid
        let decode = sha1(openID + "user")
        let getUser = await this.app.mysql.get('user', {
            u_id: decode
        });
     
        
        if (getUser) {
            return {
                status: 2,
                message: "ok",
                decode: decode,
                id: getUser.id,
                openid: openID
            };
        } else {
            var nickName = sha1(new Date().getTime())
            var avatar = "http://oxszj0so4.bkt.clouddn.com/user.png"
            var addUser = await this.app.mysql.insert("user", {
                u_id: decode,
                nickName,
                avatar
            })

            if (addUser.affectedRows == 1) {
                return {
                    status: 1,
                    decode: decode,
                    message: "ok",
                    id: addUser.insertId,
                    openid: openID

                };
            } else {
                return {
                    status: 0
                }

            }
        }

    }

    async getUserInfo(id) {

        var information = await this.app.mysql.get("user", {
            u_id: id,
        })
        if (information) {
            return {
                status: 1,
                user: information
            }
        } else {
            return {
                status: 0
            }
        }
    }


}

module.exports = User;
